<?php

namespace App\Http\Controllers\Application;

use App\Http\Controllers\Controller;
use App\Http\Requests\Application\ColumnAssetRequest;
use App\Models\Application\ColumnAsset;
use App\Models\Application\Muticolumn;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\tag_content\tag_content;
use App\Repositories\Application\ColumnAssetRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;

class ColumnAssetController extends Controller
{
    use ModelForm;

    /** @var  ColumnAssetRepository */
    private $columnAssetRepository;

    public function __construct(ColumnAssetRepository $columnAssetRepo)
    {
        $this->columnAssetRepository = $columnAssetRepo;
    }

    /**
     * Display a listing of the ColumnAsset.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.column_assets.index_header'));
            $content->description(__('application.column_assets.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new ColumnAsset.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.column_assets.create_header'));
            $content->description(__('application.column_assets.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created ColumnAsset in storage.
     *
     * @param ColumnAssetRequest $request
     *
     * @return Response
     */
    public function store(ColumnAssetRequest $request)
    {
        $input = $request->all();

        $columnAsset = $this->columnAssetRepository->create($input);

        Flash::success(__('application.column_assets.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.column_assets.index'));

    }


    public function store_new(ColumnAssetRequest $request)
    {
        $input = $request->all();
        $tag_content_id = $request->input('asset_id');
        $tag_content_id = is_array($tag_content_id) ? $tag_content_id : (strpos($tag_content_id,',') ? explode(',',$tag_content_id) : $tag_content_id);
        $tag_id = $request->input('muticolumn_id');
        $tag_content_type = $request->input('asset_type');

        // 判断是否为批量贴标签
        if (is_array($tag_content_id) && is_array($tag_id)) {
            foreach ($tag_content_id as $value) {
                foreach ($tag_id as $v){
                    $flag = ColumnAsset::where(['muticolumn_id' => $tag_id, 'asset_id' => $tag_content_id, 'asset_type' => $tag_content_type])->first();
                    if ($flag) {
                        continue;
                    } else {
                        $tag_content    = new ColumnAsset();
                        $tag_content->muticolumn_id = $v;
                        $tag_content->asset_type   = $tag_content_type;
                        $tag_content->asset_id   = $value;
                        $tag_content->save();
                    }
                }
            }
            return response()->json(['content' => '添加成功！', 'status' => true]);
        }elseif(is_array($tag_content_id) && !is_array($tag_id)){
            foreach ($tag_content_id as $value) {
                $flag = ColumnAsset::where(['muticolumn_id' => $tag_id, 'asset_id' => $tag_content_id, 'asset_type' => $tag_content_type])->first();

                if ($flag) {
                    continue;
                } else {
                    $tag_content    = new ColumnAsset();
                    $tag_content->muticolumn_id = $tag_id;
                    $tag_content->asset_type   = $tag_content_type;
                    $tag_content->asset_id   = $value;
                    $tag_content->save();
                }
            }
            return response()->json(['content' => '添加成功！', 'status' => true]);
        }elseif(!is_array($tag_content_id) && is_array($tag_id)){
            // 判断是否为批量打标签
            foreach ($tag_id as $value) {
                $flag = ColumnAsset::where(['muticolumn_id' => $tag_id, 'asset_id' => $tag_content_id, 'asset_type' => $tag_content_type])->first();

                if ($flag) {
                    continue;
                } else {
                    $tag_content    = new ColumnAsset();
                    $tag_content->muticolumn_id = $value;
                    $tag_content->asset_type   = $tag_content_type;
                    $tag_content->asset_id   = $tag_content_id;
                    $tag_content->save();
                }
            }
            return response()->json(['content' => '添加成功！', 'status' => true]);
        }elseif(!is_array($tag_content_id) && !is_array($tag_id)){
            //导入栏目
            $flag = ColumnAsset::where(['muticolumn_id' => $tag_id, 'asset_id' => $tag_content_id, 'asset_type' => $tag_content_type])->first();

            $columnAsset = $this->columnAssetRepository->create($input);
            if ($flag) {
                return response()->json(['content' => '不能重复导入,栏目数据已存在！', 'status' => false]);
            }


            $tagContent = $this->columnAssetRepository->create($input);

            return response()->json(['content' => '导入成功！', 'status' => true]);
        }

    }

    /**
     * Display the specified ColumnAsset.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $columnAsset = $this->columnAssetRepository->findWithoutFail($id);

        if (empty($columnAsset)) {
            Flash::error(__('application.column_assets.not_found'));

            return redirect(route('application.column_assets.index'));
        }

        return view('application.column_assets.show')->with('columnAsset', $columnAsset);

    }

    /**
     * Show the form for editing the specified ColumnAsset.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $columnAsset = $this->columnAssetRepository->findWithoutFail($id);

        if (empty($columnAsset)) {
            Flash::error(__('application.column_assets.not_found'));

            return redirect(route('application.column_assets.index'));
        }
        return Admin::content(function (Content $content) use ($id,$columnAsset) {

            $content->header(__('application.column_assets.edit_header'));
            $content->description(__('application.column_assets.edit_description'));

            $content->body($this->form()->edit($id));
            $content->row(view('application.column-assets.edit', ['asset_type' => $columnAsset->asset_type, 'asset_id' => $columnAsset->asset_id]));

        });
    }

    /**
     * Update the specified ColumnAsset in storage.
     *
     * @param  int              $id
     * @param ColumnAssetRequest $request
     *
     * @return Response
     */
    public function update($id, ColumnAssetRequest $request)
    {
        $columnAsset = $this->columnAssetRepository->findWithoutFail($id);

        if (empty($columnAsset)) {
            Flash::error(__('application.column_assets.not_found'));

            return redirect(route('application.column_assets.index'));
        }
        $input = $request->all();

        $columnAsset = $this->columnAssetRepository->update($input, $id);

        Flash::success(__('application.column_assets.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.column_assets.index'));
    }

    /**
     * Remove the specified ColumnAsset from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->columnAssetRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('application.column_assets.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $columnAsset = $this->columnAssetRepository->findWithoutFail($id);

        if (empty($columnAsset)) {
            Flash::error(__('application.column_assets.not_found'));

            return redirect(route('application.column_assets.index'));
        }

        if ($flag = $this->columnAssetRepository->delete($id)) {

            return response()->json(['message' => __('application.column_assets.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(ColumnAsset::class, function (Form $form) {

            $form->display('id', 'ID');
            $muticolumns = Muticolumn::pluck('title', 'id');
            $form->select('muticolumn_id', '栏目')->options($muticolumns);
            $datas = [
                '1' => '视频',
                '2' => '音频',
                '3' => '图文',
            ];
            $form->select('asset_type', '数据类型')->options($datas)->load('asset_id', route('recommend.muticolumn_reclist0_datas.datas.resources'), 'id', 'title');
            $vassetis = Vasseti::orderBy('listorder', 'asc')->pluck('title', 'id');
            $form->select('asset_id', '数据ID')->options($vassetis);

            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(ColumnAsset::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('application.column_assets.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('application.column_assets.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('application.column_assets.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('application.column_assets.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('application.column_assets.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('application.column_assets.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('application.column_assets.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('application.column_assets.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('application.column_assets.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('application.column_assets.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('muticolumn.title', '栏目')->sortable();
            $grid->column('asset_type', '媒资类型')->display(function ($val) {
                switch ($val) {
                    case '1':
                        return '<span class="badge bg-green">视频</span>';
                        break;
                    case '2':
                        return '<span class="badge bg-green">音频</span>';
                        break;
                    case '3':
                        return '<span class="badge bg-green">图文</span>';
                        break;
                    default:
                        return '';
                        break;
                }
            });
            $grid->column('asset_id', '数据')->display(function ($value) {
                switch ($this->asset_type) {
                    case '1':
                        return Vasseti::where(['id' => $value])->value('title');
                        break;
                    case '2':
                        return Vasseti::where(['id' => $value])->value('title');
                        break;
                    case '3':
                        return Vasseti::where(['id' => $value])->value('title');
                        break;
                    default:
                        return '';
                        break;
                }
            });

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '名称');

                // 栏目
                $tmpMuticolumns = Muticolumn::pluck('title', 'id');
                $filter->equal('muticolumn_id', '栏目')->select($tmpMuticolumns);
            });
        });
    }



    //栏目选择列表
    public function selectColumn(Request $request)
    {

        $viewData = array(
            'content_id'   => $request->get('content_id'),
            'content_type' => $request->get('content_type'),
        );
        return view('application.muticolumns.muticolumn-assets.addContentColumn', $viewData);
    }

    //栏目选择datatable 数据接口
    public function tableList(Request $request)
    {
        // 搜索框的值
        $search_value = $request->input('search_value');

        $data         = array();
        $data['draw'] = $request->get('draw');
        $start        = $request->get('start') ?: 0;
        $length       = $request->get('length') ?: 10;
        $order        = $request->get('order');
        $columns      = $request->get('columns');
        $search       = $request->get('search');

        $model = new Muticolumn();
        $where     = array();

        if (!empty($search_value)) {
            $where[] = array('name', 'like', '%' . $search_value . '%');
        }

        if ($order) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }
        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        list($data['recordsTotal'], $data['recordsFiltered'], $data['data']) = $model->tableList($where, $start, $length, $ord);
        return response()->json($data);
    }



}
